﻿Shader "Custom/Phong" {
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _Specular("Specular", Range(1, 20)) = 1
        _SpecColor("SpecColor", Color) = (1,1,1,1)
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
                float3 normal : TEXCOORD1;
                float3 lightDir : TEXCOORD2;
                float4 objPos : TEXCOORD3;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;

            float4 _LightColor0;

            float _Specular;
            float4 _SpecColor;

            v2f vert (appdata_full v)
            {
                v2f o;
                o.objPos = v.vertex;
                o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);
                o.uv = TRANSFORM_TEX(v.texcoord, _MainTex);
                o.normal = v.normal;
                o.lightDir = ObjSpaceLightDir(v.vertex);//把光向量从世界空间转成模型空间
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                float3 L = normalize(i.lightDir);
                float3 N = normalize(i.normal);
                float3 viewDir = normalize(ObjSpaceViewDir(i.objPos));//计算出视线

                float diff = saturate(dot(L, N));
                float3 reflection = normalize(2.0 * N * diff - L);//反射向量
                float spec = pow(max(0, dot(reflection, viewDir)), _Specular);
                float3 finalSpec = _SpecColor.rgb * spec;
                //漫反射+镜面高光+环境光
                float3 finalLight = diff * _LightColor0 + finalSpec + UNITY_LIGHTMODEL_AMBIENT;

                fixed4 col = tex2D(_MainTex, i.uv);
                return col * float4(finalLight, 1);
            }
            ENDCG
        }
    }
}
